package relu.fbs.jfm;

import java.util.*;
import java.io.*;
import relu.fbs.BadDataException;

public class JFMFarmTimeSeries {
	public final HashMap<Integer,JFMFarmData> years =new HashMap<Integer,JFMFarmData>();
	public final int farmId;
	
	/** Create a blank time series object for a farm with a particular id */
	public JFMFarmTimeSeries(int farmId_){
		farmId=farmId_;
	}
	
	/** Add a year of cropping information for this farm */
	public void addYear(JFMFarmData farmdata,int year){
		if ( farmdata.farmId != farmId ){
			throw new Error("A Farm time series can only contain data for one farm");
		}
		years.put(year, farmdata);
	}
	
	/** Create a JFMFarmDataTSAv object holding all the data across the 
	 * time series in a form that permits time averaging */
	public JFMFarmDataTSAv getAverage(int startYr,int endYr){
		JFMFarmDataTSAv yearAvFarm = null;
		boolean isFirst=true;
//		ArrayList<JFMFarmData> inyears=new ArrayList<JFMFarmData>();
		for ( int y=startYr;y<=endYr;y++){			
			if ( years.containsKey(y)){
				if ( isFirst ){
					yearAvFarm=new JFMFarmDataTSAv(years.get(y));
					isFirst=false;
				} else {
					yearAvFarm.increment(years.get(y));
				}
			}
		}
		return yearAvFarm;
	}
	
	public void exportYearsToCSV(String dirname) throws IOException, BadDataException {
		FileWriter writer=new FileWriter("./"+dirname+"/"+farmId+".csv");
		writer.write("Year,"+JFMFarmData.allToCSVHeader());
		ArrayList<Integer> sortedYears=new ArrayList<Integer>(years.keySet());
		Collections.sort(sortedYears);
		for ( int y :sortedYears){
			writer.write(y+","+years.get(y).writeAllToCSV());
		}
		writer.close();
	}
	public String printYearsToCSV() throws IOException, BadDataException {
		StringBuffer buff=new StringBuffer();
		ArrayList<Integer> sortedYears=new ArrayList<Integer>(years.keySet());
		Collections.sort(sortedYears);
		for ( int y :sortedYears){
			buff.append(y+","+years.get(y).writeAllToCSV());
		}
		return buff.toString();
	}
	
}
